//
//  CameraViewController.m
//  CumtomerCamerProject
//
//  Created by 蓓蕾 on 2021/11/23.
//

#import "CameraViewController.h"
#import <AVFoundation/AVFoundation.h>

API_AVAILABLE(ios(10.0))
@interface CameraViewController ()<AVCapturePhotoCaptureDelegate>

@property (nonatomic, retain) AVCaptureSession *session;
@property (nonatomic, retain) AVCaptureDeviceInput *input;
@property (nonatomic, retain) AVCaptureDevice *device;
@property (nonatomic, retain) AVCapturePhotoOutput *imageOutput;
@property (nonatomic, retain) AVCaptureVideoPreviewLayer *preview;
@property (nonatomic, retain) AVCapturePhotoSettings *outputSettings;

@property (nonatomic, strong) UIImage *currentImage;

@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initCameraInPosition:YES];
}

- (void)initCameraInPosition:(BOOL)isBack {
    self.session = [AVCaptureSession new];
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    NSArray *devices = [NSArray new];
//    devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    if (@available(iOS 10.0, *)) {
        AVCaptureDeviceDiscoverySession *captureDeviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera]
                                                                                                                                mediaType:AVMediaTypeVideo
                                                                                                                                 position: AVCaptureDevicePositionUnspecified];
        devices = [captureDeviceDiscoverySession devices];
    } else {
        devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    }
    
    for (AVCaptureDevice *device in devices) {
        if (isBack) {
            if ([device position] == AVCaptureDevicePositionBack) {
                _device = device;
                break;
            }
        }else {
            if ([device position] == AVCaptureDevicePositionFront) {
                _device = device;
                break;
            }
        }
    }
    
    NSError *error;
    
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if (@available(iOS 11.0, *)) {
        self.imageOutput = [[AVCapturePhotoOutput alloc] init];
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
        _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    } else if (@available(iOS 10.0, *)) {
        self.imageOutput = [[AVCapturePhotoOutput alloc] init];
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecJPEG};
        _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    } else {
        
    }
    
    
    [self.imageOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
    [self.session addOutput:self.imageOutput];
    self.preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [self.preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [self.preview setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view.layer addSublayer:self.preview];
    [self.session startRunning];
    
    UIButton *takeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    takeButton.frame = CGRectMake((self.view.frame.size.width - 70)/2, self.view.frame.size.height - 100, 70, 70);
    takeButton.layer.masksToBounds = YES;
    takeButton.layer.cornerRadius = takeButton.frame.size.height/2;
    takeButton.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7];
    [takeButton setTitle:@"拍照" forState:UIControlStateNormal];
    takeButton.titleLabel.font = [UIFont systemFontOfSize:16];
    takeButton.titleLabel.numberOfLines = 0;
    [takeButton setTitleColor:[UIColor colorWithRed:40.2f/255 green:180.2f/255 blue:247.2f/255 alpha:0.9] forState:UIControlStateNormal];
    [takeButton addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:takeButton];
    
}

- (void)takePhoto {
    if (@available(iOS 11.0, *)) {
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
        AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
        [self.imageOutput capturePhotoWithSettings:outputSettings delegate:self];
    } else if (@available(iOS 10.0, *)){
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecJPEG};
        AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
        [self.imageOutput capturePhotoWithSettings:outputSettings delegate:self];
    }
    else
    {
        
    }
}

//captureOutput:didFinishProcessingPhoto:error:

-(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
API_AVAILABLE(ios(11.0)){
    if (error != nil){
            NSLog(@"%s: %@", "Error in capture process", error.debugDescription);
        }
    
    NSData *currentImageData = nil;
        NSData *imageData = [photo fileDataRepresentation];
        
        if (imageData == nil){
            NSLog(@"%s", "unable to create image data");
        }
        currentImageData = imageData;
//        NSData *photoData = UIImageJPEGRepresentation([[UIImage alloc] initWithData:imageData], 0.0);
        
        
    
    UIImage *image = [UIImage imageWithData:currentImageData];
    _currentImage = image;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

#pragma mark AVCapturePhotoCaptureDelegate
- (void)captureOutput:(AVCapturePhotoOutput *)captureOutput didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error  API_AVAILABLE(ios(10.0)){
    
    NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
    UIImage *image = [UIImage imageWithData:data];
    _currentImage = image;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
//        _takePhotoSuccess();
    }
    NSLog(@"+++++++++++%@", msg);
    [self showImage];
}

-(void)showImage
{
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [window addSubview:imageView];
    imageView.image = _currentImage;
    imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImageView:)];
    [imageView addGestureRecognizer:tapGesture];
}

-(void)removeImageView:(UITapGestureRecognizer *)gesture
{
    UIView *gestureView = gesture.view;
    [gestureView removeFromSuperview];
}

- (void)startRunning{
    [_session startRunning];
}

- (void)stopRunning{
    [_session stopRunning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
































////
////  CameraViewController.m
////  CumtomerCamerProject
////
////  Created by 蓓蕾 on 2021/11/23.
////
//
//#import "CameraViewController.h"
//#import <AVFoundation/AVFoundation.h>
//
//API_AVAILABLE(ios(10.0))
//@interface CameraViewController ()<AVCapturePhotoCaptureDelegate>
//
//@property (nonatomic, retain) AVCaptureSession *session;
//@property (nonatomic, retain) AVCaptureDeviceInput *input;
//@property (nonatomic, retain) AVCaptureDevice *device;
//@property (nonatomic, retain) AVCapturePhotoOutput *imageOutput;
//@property (nonatomic, retain) AVCaptureVideoPreviewLayer *preview;
//@property (nonatomic, retain) AVCapturePhotoSettings *outputSettings;
//
//@property (nonatomic, strong) UIImage *currentImage;
//
//@end
//
//@implementation CameraViewController
//
//- (void)viewDidLoad {
//    [super viewDidLoad];
//    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
//
//    [self initCameraInPosition:YES];
//}
//
//- (void)initCameraInPosition:(BOOL)isBack {
//    self.session = [AVCaptureSession new];
//    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
//
//    NSArray *devices = [NSArray new];
////    devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//    if (@available(iOS 10.0, *)) {
//        AVCaptureDeviceDiscoverySession *captureDeviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera]
//                                                                                                                                mediaType:AVMediaTypeVideo
//                                                                                                                                 position: AVCaptureDevicePositionUnspecified];
//        devices = [captureDeviceDiscoverySession devices];
//    } else {
//        devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//    }
//
//    for (AVCaptureDevice *device in devices) {
//        if (isBack) {
//            if ([device position] == AVCaptureDevicePositionBack) {
//                _device = device;
//                break;
//            }
//        }else {
//            if ([device position] == AVCaptureDevicePositionFront) {
//                _device = device;
//                break;
//            }
//        }
//    }
//
//    NSError *error;
//
//    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
//    if ([self.session canAddInput:self.input]) {
//        [self.session addInput:self.input];
//    }
//    if (@available(iOS 11.0, *)) {
//        self.imageOutput = [[AVCapturePhotoOutput alloc] init];
//        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
//        _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
//    } else if (@available(iOS 10.0, *)) {
//        self.imageOutput = [[AVCapturePhotoOutput alloc] init];
//        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecJPEG};
//        _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
//    } else {
//
//    }
//
//
//    [self.imageOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
//    [self.session addOutput:self.imageOutput];
//    self.preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
//    [self.preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
//    [self.preview setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//    [self.view.layer addSublayer:self.preview];
//    [self.session startRunning];
//
//    UIButton *takeButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    takeButton.frame = CGRectMake((self.view.frame.size.width - 70)/2, self.view.frame.size.height - 100, 70, 70);
//    takeButton.layer.masksToBounds = YES;
//    takeButton.layer.cornerRadius = takeButton.frame.size.height/2;
//    takeButton.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7];
//    [takeButton setTitle:@"拍照" forState:UIControlStateNormal];
//    takeButton.titleLabel.font = [UIFont systemFontOfSize:16];
//    takeButton.titleLabel.numberOfLines = 0;
//    [takeButton setTitleColor:[UIColor colorWithRed:40.2f/255 green:180.2f/255 blue:247.2f/255 alpha:0.9] forState:UIControlStateNormal];
//    [takeButton addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:takeButton];
//
//}
//
//- (void)takePhoto {
//    if (@available(iOS 11.0, *)) {
//        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
//        AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
//        [self.imageOutput capturePhotoWithSettings:outputSettings delegate:self];
//    } else if (@available(iOS 10.0, *)){
//        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecJPEG};
//        AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
//        [self.imageOutput capturePhotoWithSettings:outputSettings delegate:self];
//    }
//    else
//    {
//
//    }
//}
//
////captureOutput:didFinishProcessingPhoto:error:
//
//-(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
//API_AVAILABLE(ios(11.0)){
//    if (error != nil){
//            NSLog(@"%s: %@", "Error in capture process", error.debugDescription);
//        }
//
//    NSData *currentImageData = nil;
//        NSData *imageData = [photo fileDataRepresentation];
//
//        if (imageData == nil){
//            NSLog(@"%s", "unable to create image data");
//        }
//        currentImageData = imageData;
////        NSData *photoData = UIImageJPEGRepresentation([[UIImage alloc] initWithData:imageData], 0.0);
//
//
//
//    UIImage *image = [UIImage imageWithData:currentImageData];
//    _currentImage = image;
//    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//}
//
//#pragma mark AVCapturePhotoCaptureDelegate
//- (void)captureOutput:(AVCapturePhotoOutput *)captureOutput didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error  API_AVAILABLE(ios(10.0)){
//
//    NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
//    UIImage *image = [UIImage imageWithData:data];
//    _currentImage = image;
//    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//}
//
//- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
//    NSString *msg = nil ;
//    if(error != NULL){
//        msg = @"保存图片失败" ;
//    }else{
//        msg = @"保存图片成功" ;
////        _takePhotoSuccess();
//    }
//    NSLog(@"+++++++++++%@", msg);
//    [self showImage];
//}
//
//-(void)showImage
//{
//
//    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
//    [window addSubview:imageView];
//    imageView.image = _currentImage;
//    imageView.userInteractionEnabled = YES;
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImageView:)];
//    [imageView addGestureRecognizer:tapGesture];
//}
//
//-(void)removeImageView:(UITapGestureRecognizer *)gesture
//{
//    UIView *gestureView = gesture.view;
//    [gestureView removeFromSuperview];
//}
//
//- (void)startRunning{
//    [_session startRunning];
//}
//
//- (void)stopRunning{
//    [_session stopRunning];
//}
//
///*
//#pragma mark - Navigation
//
//// In a storyboard-based application, you will often want to do a little preparation before navigation
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//    // Get the new view controller using [segue destinationViewController].
//    // Pass the selected object to the new view controller.
//}
//*/
//
//@end
